package edu.hitsz;

import edu.hitsz.rank.RankDao;
import edu.hitsz.rank.RankDaoImpl;
import edu.hitsz.rank.RankInfo;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class RankTable {
    private JPanel mainPanal;
    private JPanel topPanel;
    private JScrollPane tableScrollPanel;
    private JTable scoreTable;
    private JLabel headerLabel;
    private JPanel bottomPanel;
    private JButton deleteButton;

    public RankTable(RankDao rankDao) {
        List<RankInfo> rankInfoList = rankDao.getRankInfoList();
        
        String[] columnName = {"排名", "玩家名", "得分", "创建时间"};
        String[][] tableData = new String[rankInfoList.size()][columnName.length];
        for (int i = 0; i < rankInfoList.size(); i++) {
            RankInfo rankInfo = rankInfoList.get(i);
            tableData[i][0] = String.valueOf(i + 1);
            tableData[i][1] = String.valueOf(rankInfo.getScore());
            tableData[i][2] = rankInfo.getUser_name();
            tableData[i][3] = rankInfo.getCreate_time();
        }

        DefaultTableModel model = new DefaultTableModel(tableData, columnName){
            @Override
            public boolean isCellEditable(int row, int col){
                return false;
            }
        };

        scoreTable.setModel(model);
        tableScrollPanel.setViewportView(scoreTable);

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int row = scoreTable.getSelectedRow();
                System.out.println(row);
                int result = JOptionPane.showConfirmDialog(deleteButton,
                        "是否确定中删除？");
                if (JOptionPane.YES_OPTION == result && row != -1) {
                    rankInfoList.remove(row);
                    rankInfoList.sort((o1, o2) -> o2.getScore() - o1.getScore());
                    for (int i = 0; i < rankInfoList.size(); i++) {
                        RankInfo rankInfo = rankInfoList.get(i);
                        tableData[i][0] = String.valueOf(i + 1);
                        tableData[i][1] = String.valueOf(rankInfo.getScore());
                        tableData[i][2] = rankInfo.getUser_name();
                        tableData[i][3] = rankInfo.getCreate_time();
                    }

                    DefaultTableModel model = new DefaultTableModel(tableData, columnName){
                        @Override
                        public boolean isCellEditable(int row, int col){
                            return false;
                        }
                    };
                    scoreTable.setModel(model);
                    tableScrollPanel.setViewportView(scoreTable);
                }
            }
        });
        
    }

    public JPanel getMainPanal() {return mainPanal;}

}
